/**
 * Kohadmin Forms
 *
 * @copyright (c) 2009 Nobis Stultius IT
 * @author Thomas Filius mail@thomasfilius.com
 */


var addOrder = {

	getClientInfo : function (e)
	{
		jQuery.getJSON(uri2app + "customers/view/" + e.value, function(data)
		{
			jQuery("#customer_debitnumber").html(data.debitnumber||"Niet beschikbaar");
			jQuery("#customer_address").html(data.address||"Niet beschikbaar");
		});
	},
	addProduct : function (e)
	{		
		OrderItems.addItem(e.val(), e.text(), 0, e.attr("price"));		
		OrderItems.rebuild();		
	}
}

/**
 * Static classes
 */


function Item (i, pid, pn, q, p) {
	this.index = i;
	this.product_name = pn;
	this.product_id = pid;
	this.quantity = q;
	this.price = p;

	Item.prototype.returnHTML = function () {
		t = '<tr>';
		t+= '<td><img src="' + uri2mod + '/assets/img/icon_delete.gif" /></td>';
		t+= '<td><input type="hidden" name="product_id[' + this.index + ']" value="' + this.product_id + '" />' + this.product_name + '</td>';
		t+= '<td><input type="text" name="quantity[' + this.index + ']" value="' + this.quantity + '" class="quantity" size="4" /></td>';
		t+= '<td>&euro; <input type="text" name="price[' + this.index + ']" value="' + this.price + '" class="valuta" size="4" /></td>';
		t+= '<td class="valuta">&euro; <span class="i_total">' + this.total() + '</span></td>';
		t+= '</tr>';
		return t;
	}

	Item.prototype.total = function () {
		return this.quantity * this.price;
	}
}

var OrderItems = {
	items: new Array(),

	addItem: function (product_id, product_name, quantity, price) {
		this.items.push(new Item(this.items.length, product_id, product_name, quantity, price));		
	},

	returnHTML: function () {
		if (this.items.length == 0) {
			return "<tr><td colspan='5'>Voeg een product toe</td></tr>";
		}
		t = "";
		for (i=0, il=this.items.length; i<il; i++) {
			t += this.items[i].returnHTML();
		}
		return t;
	},
	
	rebuild: function () {		
		jQuery("tbody.orderitems").html(this.returnHTML());
		jQuery("span.subtotal").html(this.subTotal());
	},
	
	subTotal: function () {
		sub = 0;
		
		for (i=0, il=this.items.length; i<il; i++) {
			sub += this.items[i].total();
		}		
		return sub;
	}	
}